const app = getApp()
import { confirm, create } from '../../../api/order'

Page({
  data: {
    header: app.global.headerHeight,
    theme: '',
    back: true,
    title: '确认订单',
    loading: true,
    submitLoading: false,
    disabled: true, // 是否可提交
    init: true, // 初始化请求标记
    couponWindow: false,
    couponShowType: 30,
    timeWindow: false,
    times: [],
    timeLeftIndex: 0,
    timeRightIndex: 0,
    timeText: '',
    locations: [],
    locations_id: 0,
    location_name: '',
    location_address: '',
    locationWindow: false,
    setting: {},
    tabIndex: 0,
    methods: [],
    order: null,
    template: [],
    form: {
      address: 0,
      method: 0,
      sku: '',
      lon: '0',
      lat: '0'
    },
    contact_error: false,
    contact_error_message: '',
    phone_error: false,
    phone_error_message: '',
    submit: {
      address: 0,
      coupon: 0, // 优惠劵ID
      coupon_amount: 0, // 优惠卷金额
      discount: 0, // 优惠金额合计
      logistics: 0, // 物流费
      invoice: 10, // 是否开具发票
      price: 0, // 商品总价
      payment: 0, // 实际支付价格
      remark: '', // 备注信息
      contact: '', // 自提联系人
      phone: '', // 自提联系人手机号
      day: 0,
      time: '',
      location: 0,
      source: 20, // 来自小程序提交的订单
      order: ''
    },
    abnor: {
      title: '暂无可用的优惠卷~'
    }
  },
  onLoad (options) {
    this.setData({ theme: app.global.theme })
    wx.setStorageSync('address', 0)
    wx.setStorageSync('invoice', 10)
    this.fetch()
  },
  onShow () {
    this.changeInvoice()
    this.changeAddress()
  },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () { },

  // ===================methon================

  /**
   * 切换收货地址
   */
  changeAddress () {
    const address = wx.getStorageSync('address')
    if (!this.data.init && address && address != this.data.form.address) {
      const form = this.data.form
      form.address = address
      this.setData({ form: form })
      this.fetch()
    }
  },
  /**
   * 切换开具发票
   */
  changeInvoice () {
    const submit = this.data.submit
    submit.invoice = wx.getStorageSync('invoice')
    this.setData({
      setting: app.global.setting.order,
      submit: submit
    })
  },
  fetch () {
    const that = this
    const form = this.data.form
    const submit = this.data.submit
    that.data.init ? that.setData({ loading: true }) : wx.showLoading()
    wx.getLocation({
      success (res) {
        form.lat = res.latitude.toString()
        form.lon = res.longitude.toString()
      },
      fail () {
        app.toast('您已拒绝授权，系统无法获取您的位置')
      },
      complete () {
        form.sku = JSON.stringify(wx.getStorageSync('sku'))
        form.address = wx.getStorageSync('address')
        
        confirm(form).then(res => {
          const { methods, order, location, template } = res.data
          form.method = order.logistics_method
          form.address = order.logistics ? order.logistics.id : 0

          submit.method = order.logistics_method
          submit.address = order.logistics ? order.logistics.id : 0
          submit.logistics = order.logistics_fee
          submit.price = order.goods_price
          submit.order = JSON.stringify(order.submit_order)

          that.setData({
            methods: that.getMethods(methods),
            order: order,
            form: form,
            submit: submit,
            locations: location,
            template: template
          })
          that.total()
        })
          .finally(() => {
            if (!that.data.init) wx.hideLoading()
            that.setData({
              loading: false,
              init: false
            })
          })
      }
    })
  },
  handleSubmit () {
    const that = this
    const submit = that.data.submit
    if (submit.method == 30) {
      if (submit.contact.trim() == '') {
        app.toast('请输入提货人姓名')
        return false
      }
      if (submit.phone.trim() == '') {
        app.toast('请输入提货人手机号')
        return false
      }

      if (submit.time == '') {
        app.toast('请选择自提地点和时间')
        return false
      }
    }

    that.setData({ submitLoading: true })
    wx.requestSubscribeMessage({
      tmplIds: that.data.template,
      complete () {
        /** ***提交订单****/
        create(submit).then(resp => {
          wx.showLoading({ title: '支付中...' })
          wx.requestPayment({
            'timeStamp': resp.data.timeStamp,
            'nonceStr': resp.data.nonceStr,
            'package': resp.data.package,
            'signType': resp.data.signType,
            'paySign': resp.data.paySign,
            'success': function (res) {
              app.toast('支付成功', function () {
                wx.redirectTo({
                  url: '/pages/order/detail/index?id=' + resp.data.id
                })
              }, 'success')
            },
            fail: function (res) {
              wx.redirectTo({
                url: '/pages/order/detail/index?id=' + resp.data.id
              })
            },
            complete: function (res) {
              wx.hideLoading()
            }
          })
        })
          .catch(e => {
            app.toast(e.msg)
          })
          .finally(() => {
            that.setData({ submitLoading: false })
          })
      }
    })
  },
  /**
   * 计算支付金额
   */
  total () {
    const submit = this.data.submit
    submit.discount =
    parseInt((submit.coupon_amount * 100).toFixed(0)) // TODO 可能会增加其他优惠额 +
    submit.discount = parseFloat((submit.discount / 100).toFixed(2))

    submit.payment =
    parseInt((submit.price * 100).toFixed(0)) +
    parseInt((submit.logistics * 100).toFixed(0)) -
    parseInt((submit.discount * 100).toFixed(0))

    submit.payment = parseFloat((submit.payment / 100).toFixed(2))
    submit.payment = submit.payment < 0 ? 0 : submit.payment

    let disabled = true
    if (submit.address > 0 && submit.payment > 0) {
      disabled = false
    } else {
      disabled = true
    }

    this.setData({
      submit: submit,
      disabled: disabled
    })
  },
  /**
   * 切换物流方式
   */
  changeLogistics (event) {
    const form = this.data.form
    form.method = this.data.methods[event.detail.index].key

    this.setData({
      form: form,
      init: false
    })
    this.fetch()
  },
  getMethods (data) {
    const result = []
    data.forEach((value) => {
      if (value == 10) {
        result.push({
          key: 10,
          name: '快递发货'
        })
      }
      if (value == 20) {
        result.push({
          key: 20,
          name: '同城配送'
        })
      }
      if (value == 30) {
        result.push({
          key: 30,
          name: '上门自提'
        })
      }
    })
    return result
  },

  /** ************优惠卷区 Start*************/
  /**
   * 选择使用优惠卷
   */
  selectCoupon (event) {
    const id = event.currentTarget.dataset.id
    const type = event.currentTarget.dataset.type
    const discount = event.currentTarget.dataset.discount // 折扣
    const amount = event.currentTarget.dataset.amount // 优惠金额

    const submit = this.data.submit
    const price = submit.price * 100 // 商品总价

    submit.coupon_amount = type == 10 ? amount : ((price - (price * (discount / 10))) / 100).toFixed(2)
    submit.coupon = id

    this.setData({
      submit: submit,
      couponWindow: false
    })
    this.total()
  },
  /**
   * 不使用优惠卷
   */
  cancelCoupon () {
    const submit = this.data.submit
    submit.coupon = 0
    submit.coupon_amount = 0
    this.setData({
      submit: submit,
      couponWindow: false
    })
    this.total()
  },
  showCoupon () {
    this.setData({ couponWindow: true })
  },
  hideCoupon () {
    this.setData({ couponWindow: false })
  },
  /** ************优惠卷区 End*************/

  /** ************自提地点区 Start************/
  showLocation () {
    this.setData({ locationWindow: true })
  },
  hideLocation () {
    this.setData({ locationWindow: false })
  },
  changeLocatioon (event) {
    this.setData({ locations_id: event.currentTarget.dataset.id })
  },
  submitLocation () {
    const id = this.data.locations_id
    if (!id) {
      app.toast('请选择自提地点')
      return false
    }

    const submit = this.data.submit
    submit.location = id
    this.data.locations.forEach(item => {
      if (item.id == id) {
        this.setData({
          submit: submit,
          location_name: item.address_name,
          location_address: item.address,
          times: item.times,
          locationWindow: false
        })
      }
    })
  },
  phoneCall (event) {
    wx.makePhoneCall({
      phoneNumber: event.currentTarget.dataset.phone
    })
  },
  /** ***********自提地点区 End*************/

  /** ************自提时间区 Start************/
  showTime () {
    if (!this.data.times.length) {
      app.toast('请先选择自提地点')
      return false
    }
    this.setData({ timeWindow: true })
  },
  hideTime () {
    this.setData({ timeWindow: false })
  },
  timeLeftClick (event) {
    this.setData({
      timeLeftIndex: event.detail.index || 0
    })
  },
  timeRightClick (event) {
    const timeRightIndex = this.data.timeRightIndex === event.detail.id ? null : event.detail.id
    this.data.timeText = event.detail.text

    this.setData({
      timeRightIndex: timeRightIndex
    })
  },
  submitTime () {
    if (!this.data.timeText) {
      app.toast('请选择自提时间')
      return false
    }
    const submit = this.data.submit
    submit.day = this.data.timeLeftIndex
    submit.time = this.data.timeText

    this.setData({
      submit: submit,
      timeWindow: false
    })
  },
  /** ***********自提时间区 End*************/

  setContact (event) {
    const submit = this.data.submit
    submit.contact = event.detail
    this.setData({ submit: submit })
  },
  checkContact () {
    const submit = this.data.submit
    if (submit.contact.trim() == '') {
      this.setData({
        contact_error: true,
        contact_error_message: '请输入提货人姓名'
      })
    } else {
      this.setData({
        contact_error: false,
        contact_error_message: ''
      })
    }
  },
  setPhone (event) {
    const submit = this.data.submit
    submit.phone = event.detail
    this.setData({ submit: submit })
  },
  checkPhone () {
    const submit = this.data.submit
    if (!(/^1(3|4|5|7|8)\d{9}$/.test(submit.phone))) {
      this.setData({
        phone_error: true,
        phone_error_message: '手机号格式错误'
      })
    } else {
      this.setData({
        phone_error: false,
        phone_error_message: ''
      })
    }
  },
  setRemark (event) {
    const submit = this.data.submit
    submit.remark = event.detail
    this.setData({ submit: submit })
  },
  redirect (event) {
    app.redirect(event.currentTarget.dataset.url)
  }
})